InitArray.java

C:\jhtp_10th\ch07\fig07_02>java InitArray
Index   Value
    0       0
    1       0
    2       0
    3       0
    4       0
    5       0
    6       0
    7       0
    8       0
    9       0


InitArray.java

// Fig. 7.2: InitArray.java
// Initializing the elements of an array to default values of zero.

public class InitArray 
{
   public static void main(String[] args)
   {
      // declare variable array and initialize it with an array object  
      int[] array = new int[10]; // new creates the array object 

      System.out.printf("%s%8s%n", "Index", "Value"); // column headings
   
      // output each array element's value 
      for (int counter = 0; counter < array.length; counter++)
         System.out.printf("%5d%8d%n", counter, array[counter]);
   } 
} // end class InitArray

Note the %n in the printf statement - this is Java preferred way of specifying a newline character

In the Java programming language, the \n escape always generates the linefeed character (\u000A). Don't use \n unless you specifically want a linefeed character. To get the correct line separator for the local platform, use %n.

Reference

Java Tutorial on Formatting


Maintained by John Loomis, updated Tue Jan 24 15:27:29 2017